package com.dongliu.controller;

import com.dongliu.domain.Admin;
import com.dongliu.domain.Book;
import com.dongliu.domain.User;
import com.dongliu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        System.out.println(book);
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR, flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR, flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR, flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败，请重试！";
        return new Result(code, book, msg);
    }

//    @GetMapping("/{name}")
//    public Result getByName(@PathVariable String name) {
//        Book book = bookService.getByName(name);
//        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = book != null ? "" : "数据查询失败，请重试！";
//        return new Result(code, book, msg);
//    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        User user = (User) request.getSession().getAttribute("user");
        if(admin == null && user == null)
            return new Result(Code.LOGIN_ERR, null, "请登录后再执行操作！");
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "":"数据查询失败，请重试！";
        return new Result(code, bookList, msg);
    }
}
